
package com.jf.cloud.order.listener;

import com.jf.cloud.common.order.constant.ReturnProcessStatusEnum;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.order.dto.multishop.OrderRefundDTO;
import com.jf.cloud.order.service.OrderRefundService;
import com.jf.cloud.order.vo.OrderRefundVO;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 订单退款事务监听
 * @author zz
 * @date 2021/1/7
 */
@Component
@RocketMQTransactionListener(rocketMQTemplateBeanName = "orderRefundTemplate",maximumPoolSize = 20)
public class OrderRefundTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderRefundService orderRefundService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        OrderRefundVO orderRefundVO = Json.parseObject((byte[])msg.getPayload(), OrderRefundVO.class);

        OrderRefundDTO orderRefundParam = (OrderRefundDTO)arg;
        // 同意退款
        int updateStats = orderRefundService.agreeRefund(orderRefundVO,orderRefundParam);




        if (updateStats == 0) {
            // 如果啥都没有更新，就检查一下
            return checkLocalTransaction(msg);
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        OrderRefundVO orderRefundVO = Json.parseObject((byte[])msg.getPayload(), OrderRefundVO.class);
        OrderRefundVO dbRefundStatus = orderRefundService.getByRefundId(orderRefundVO.getRefundId());
        if (!Objects.equals(dbRefundStatus.getReturnMoneySts(), ReturnProcessStatusEnum.PROCESSING.value())) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }




}
